#include "liveclient.h"
#include <stdio.h>
#include <iostream>
#include <boost/thread/thread.hpp>
#include "pfcmu_config.h"
#include "nodeconfig.h"
#include "graphicsiplimgobject.h"

LiveClient::LiveClient(QObject *parent) :
        QObject(parent)
{
    isRunning = false;
    m_Buffer = NULL;
}

void LiveClient::connectNode(char *nodeName, int idxCam)
{
    if(!isRunning)
    {
        isRunning = true;
        m_CurrNode = std::string(nodeName);
        m_CurrCam = idxCam;
        const char* netport = PORT.c_str();
        boost::thread netTrd(boost::bind(&LiveClient::m_Connect,this,nodeName, netport, idxCam));
    }
}

void LiveClient::disconnectNode()
{
    if(isRunning)
    {
        isRunning = false;
    }
}

void LiveClient::m_Connect(char *nodeName, const char *nodePort, int idxCam)
{
    IplImage *blackBuf = NULL;
    try
    {
        using namespace boost::asio::ip;
        tcp::iostream nodeStream(nodeName, nodePort);
        std::string header;
        for(int i=0;i<26;i++)
        {
            std::getline(nodeStream, header);
            std::cout << header << std::endl;
        }
        PFCMU::timestamp_t ts_prev=0;
        for(;;)
        {
            char text[1024];
            snprintf(text, sizeof(text), "PGM %d", idxCam);
            nodeStream << text << std::endl;

            //receive PGM data
            int width, height, color;
            std::string strWidth,strHeight,strColor;
            std::getline(nodeStream,header);
            std::getline(nodeStream,strWidth);
            std::getline(nodeStream,strHeight);
            std::getline(nodeStream,strColor);
            //nodeStream.get();
            std::cout << header << strWidth << strHeight << strColor << std::endl;

            if(NULL == blackBuf || blackBuf->width != width || blackBuf->height != height)
            {
                cvReleaseImage(&blackBuf);
                blackBuf = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1);
                std::cout << "IMG created" << std::endl;
            }

            //receive the image
            nodeStream.read(blackBuf->imageData, 640*480);
            std::cout << "IMG received"<< std::endl;

            cvCopy(blackBuf,m_Buffer);

            std::cout << "buf copied" << std::endl;

            emit receivedImg();

            PFCMU::timestamp_t ts_curr = PFCMU::get_timestamp(blackBuf->imageData);
            ts_prev = ts_curr;

            if(!isRunning)
            {
                std::cout << "BYE" << std::endl;
                nodeStream << "BYE" << std::endl;
                cvReleaseImage(&blackBuf);
                break;
            }

        }
    }
    catch(std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }
}

void LiveClient::setImgObject(GraphicsIplImgObject *img)
{
    m_ImgObj = img;
    this->setBuffer(m_ImgObj->getOrigIplImage());
}

void LiveClient::setBuffer(IplImage *ipl)
{
    m_Buffer = ipl;
}


